var passwordRegex1="0123456789";
var passwordRegex2="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var passwordRegex3=",./;'[]\\`-=<>?:\"{}|~!@#$%^&*()_+";

var passwordErrMsg;
var passwordRetVal;

jQuery.validator.addMethod("password",
    function(password, element, param) {
        if (!this.depend(param, element)) {
            return "dependency-mismatch";
        }

        passwordErrMsg = "";
        passwordRetVal = true;

        if (password.indexOf(" ") >= 0) {
            passwordErrMsg = "密码不能包含空格";
            passwordRetVal = false;
        } else if (password.length < 6 || password.length > 16) {
            passwordErrMsg = "密码必须为6～16位字符";
            passwordRetVal = false;
        } else {
            passwordRetVal = validatePassword(password);
            if (!passwordRetVal) {
                passwordErrMsg = "密码必须为6~16位字符，且至少包含数字、字母(区分大小写)、符号中的两种。";
            }
        }

        $.validator.messages.password = passwordErrMsg;
        return passwordRetVal;
    },
    passwordErrMsg
);

var nicknameErrMsg;
var nicknameRetVal = true;
jQuery.validator.addMethod("nickname", function(value, element, param) {
    if ( !this.depend(param, element))
        return "dependency-mismatch";

    nicknameErrMsg = "";
    nicknameRetVal = true;

    var str = value || element.value;

    var pattern = /^[0-9a-zA-Z_-]+$/;
    if (str.length<4){
        nicknameErrMsg="用户名必须为4~30位字符。";
        nicknameRetVal = false;
    }else if (str.length>30){
        nicknameErrMsg="用户名必须为4~30位字符。";
        nicknameRetVal = false;
    }else if (str.indexOf(" ")>=0) {
        nicknameErrMsg="用户名不能包含空格。";
        nicknameRetVal = false;
    }else if(!pattern.test(str)){
        nicknameErrMsg="用户名只能包含英文字母、数字、“-”和“_”。";
        nicknameRetVal = false;
    } else if(str.substr(0,1) == "_" || str.substr(0,1) == "-"){
        nicknameErrMsg= "用户名不能以“-”、“_”开头。";
        nicknameRetVal = false;
    }

    $.validator.messages.nickname = nicknameErrMsg;
    return nicknameRetVal;
},  nicknameErrMsg);

function validatePassword(password) {
    var hasNum = 0;
    var hasChar = 0;
    var hasSpecialChar = 0;
    if (password.length < 6 || password.length > 16) {
        return false;
    }
    for (var i = 0; i < password.length; i++) {
        if (passwordRegex1.indexOf(password.charAt(i)) > -1) {
            hasNum = 1;
        } else if (passwordRegex2.indexOf(password.charAt(i)) > -1) {
            hasChar = 1;
        } else if (passwordRegex3.indexOf(password.charAt(i)) > -1) {
            hasSpecialChar = 1;
        } else {
            return false;
        }
    }

    if (hasNum + hasChar + hasSpecialChar < 2) {
        return false;
    }

    return true;
}